import 'dart:convert';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rider/main/page/image_viewer_page.dart';
import 'package:flutter_rider/main/models/waybill_record_model.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/main/widgets/ext/u_shape.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';

class OrderTrackLayout extends StatelessWidget {
  List<WaybillRecordModel> records = [];
  dynamic data;
  var lastStatus = 0;
  BuildContext? context;

  OrderTrackLayout(this.data, {Key? key}) : super(key: key) {
    List list = data["waybill_mission_record"];

    list.forEach((element) { 
      records.add(WaybillRecordModel.fromMap(element));
    });
    

    // records?.removeWhere((element) {
    //   var st = element["status"];
    //   return st == 0 ;
    // });
    records = records.reversed.toList();
  }

  @override
  Widget build(BuildContext context) {
    context = context;
    if (records == null ) {
      return 0.hspace;
    }
    List<Widget> children = [];
    for (int i = 0; i < records.length; i++) {
      var record = records[i];
      var st = record.status;
      if (st == 0) {  //
        children.add(_render0(i));
      } else if (st == 1) { // 已分配
        children.add(_render1(i));
      } else if (st == 2) { // 取货中
        children.add(_render2(i));
      } else if (st == 3) { // 已到达取货点，装货中
        children.add(_render3(i));
      } else if(st == 4){  //变更卸货地址
        children.add(_render4(i));
      } else if (st == 5 ) { // 装货完成
        children.add(_render5(i));
      } else if (st == 6) { // 装货完成配送中
        children.add(_render6(i));
      } else if (st == 7) { // 已到送货点，卸货中
        children.add(_render7(i));
      } else if (st == 9) { // 已完成
        children.add(_render9(i));
      } else if (st == 20) { // 已取消
        children.add(_render20(i));
      }
      // else if (st == 21) { //
      //   children.add(_renderCancel(i));
      // }
    }
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.rpx),
      margin: EdgeInsets.symmetric(horizontal: 12.rpx),
      decoration: BoxDecoration(
        color: UIColor.color_content,
        borderRadius:  BorderRadius.vertical(top: Radius.circular(12.rpx)),
      ),
      child: SingleChildScrollView(
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          UText.get("履约轨迹", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
          10.hspace,
          ...children.reversed.toList(),
        ]),
      )
    );
  }

  Widget _renderLeftLine(int index) {
    var last = index == records.length - 1;
    var fist = index == 0;
    Widget circle;
    if (last) {
      circle = Stack(
        alignment: Alignment.center,
        children: [
          UShape.getCircle(size: 9.rpx, color: const Color(0xffB6E3FA)),
          UShape.getCircle(size: 8.rpx, color: UIColor.color_primary),
        ],
      );
    } else {
      circle = UShape.getCircle(size: 9.rpx, color: const Color(0xffd2d2d2));
    }
    return Column(
      children: [
        Expanded(
          child:
              Container(width: 1.rpx, color: last ? Colors.transparent : const Color(0xffd2d2d2)),
        ),
        circle,
        Expanded(
          child:
              Container(width: 1.rpx, color: fist ? Colors.transparent : const Color(0xffd2d2d2)),
        ),
      ],
    );
  }

  Widget _render0(int index) {
    var record = records[index];
    // var _txt = "已下单成功";
    // if(record.desc!="" && record.desc!=null) {
    //   _txt = record.desc ;
    // }
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  8.hspace,
                  UText.get(record.desc, UIColor.color_t1, 14.rpx),
                  4.hspace,
                  UText.get(record.created_time, UIColor.color_t3, 12.rpx),
                  8.hspace,
                ],
              ))
        ],
      ),
    );
  }

  Widget _render1(int index) {
    var record = records[index];
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              8.hspace,
              RichText(
                text: TextSpan(
                  text: "已分配订单至无人车 (",
                  style: TextStyle(
                    color: UIColor.color_t1,
                    fontSize: 14.rpx,
                  ),
                  children: [
                    TextSpan(
                        text: record.car_no, style: const TextStyle(color: UIColor.color_primary)),
                    const TextSpan(text: ") 进行履约", style: TextStyle(color: UIColor.color_t1)),
                  ],
                ),
              ),
              4.hspace,
              UText.get(record.created_time, UIColor.color_t3, 12.rpx),
              8.hspace,
            ],
          ))
        ],
      ),
    );
  }

  Widget _render2(int index) {
    var record = records[index];
    // var _txt = "已发车, 正在取货途中";
    // if(record.desc!="" && record.desc!=null) {
    //   _txt = record.desc;
    // }
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              8.hspace,
              record.desc!="" && record.desc.isEmpty?UText.get("已发车, 正在取货途中", UIColor.color_t1, 14.rpx):RichText(
                  text: TextSpan(
                    text: "已分配任务至无人车（",
                    style: TextStyle(
                      color: UIColor.color_t1,
                      fontSize: 14.rpx,
                    ),
                    children: [
                      TextSpan(text: record.car_no, style: const TextStyle(color: UIColor.color_primary) ),
                      const TextSpan(text: "），进行履约", style: TextStyle(color: UIColor.color_t1)),


                    ],
                  ),
                ),
              4.hspace,
              UText.get(record.created_time, UIColor.color_t3, 12.rpx),
              8.hspace,
            ],
          ))
        ],
      ),
    );
  }

  Widget _render20(int index) {
    var record = records[index];
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  8.hspace,
                  record.desc!="" && record.desc.isNotEmpty?RichText(
                    text: TextSpan(
                      text: "操作员",
                      style: TextStyle(
                        color: UIColor.color_t1,
                        fontSize: 14.rpx,
                      ),
                      children: [
                        TextSpan(text: record.operator_name, style: const TextStyle(color: UIColor.color_primary) ),
                        const TextSpan(text: "已取消任务（", style: TextStyle(color: UIColor.color_t1)),
                        TextSpan(text: record.remark, style: const TextStyle(color: UIColor.color_primary) ),
                        const TextSpan(text: "）", style: TextStyle(color: UIColor.color_t1) ),
                      ],
                    ),
                  ):UText.get("商家已取消订单", UIColor.color_t1, 14.rpx),
                  4.hspace,
                  UText.get(record.created_time, UIColor.color_t3, 12.rpx),
                  8.hspace,
                ],
              ))
        ],
      ),
    );
  }

  Widget _render3(int index) {
    var record = records[index];
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  8.hspace,
                  RichText(
                    text: TextSpan(
                      text: "车辆已到取货地点（",
                      style: TextStyle(
                        color: UIColor.color_t1,
                        fontSize: 14.rpx,
                      ),
                      children: [
                        TextSpan(text: record.pick_station_name, style: const TextStyle(color: UIColor.color_primary) ),
                        const TextSpan(text: "）正在装货", style: TextStyle(color: UIColor.color_t1)),
                      ],
                    ),
                  ),
                  4.hspace,
                  UText.get(record.created_time, UIColor.color_t3, 12.rpx),
                  8.hspace,
                ],
              )
          )
        ],
      ),
    );
  }

  Widget _render4(int index) {
    var record = records[index];
    /// 主操作员 + 协作员
    // String loaders = record.loaders;
    // String str = "";
    // if(loaders.isNotEmpty ) {
    //   List list = [];
    //   list = jsonDecode(loaders);
    //   list.forEach((element) {
    //     str = str + '、' + element["name"];
    //   });
    // }
    // var txt = record.operator_name + str ;
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  RichText(
                    text: TextSpan(
                      text: record.operator_name+"变更卸货地址至（",
                      style: TextStyle(
                        color: UIColor.color_t1,
                        fontSize: 14.rpx,
                      ),
                      children: [
                        TextSpan(text: record.station_name , style: const TextStyle(color: UIColor.color_primary) ),
                        const TextSpan(text: "）", style: TextStyle(color: UIColor.color_t1)),


                      ],
                    ),
                  ),
                  //UText.get(txt, UIColor.color_primary, 14.rpx),
                  4.hspace,
                  UText.get(record.created_time, UIColor.color_t3, 12.rpx),
                  8.hspace,
                  ..._renderImages(record.images,record),
                ],
              )
          )
          // Expanded(
          //   child: Column(
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     children: [
          //       8.hspace,
          //       UText.get(record.desc, UIColor.color_t1, 14.rpx),
          //       4.hspace,
          //       UText.get(record.created_time, UIColor.color_t3, 12.rpx),
          //       8.hspace,
          //       ..._renderImages(record.images,record),
          //     ],
          //   ),
          // ),
        ],
      ),
    );
  }

  Widget _render5(int index) {
    var record = records[index];
    /// 主操作员 + 协作员
    String loaders = record.loaders;
    String str = "";
    if(loaders.isNotEmpty ) {
      List list = [];
      list = jsonDecode(loaders);
      list.forEach((element) {
        str = str + '、' + element["name"];
      });
    }
    var txt = record.operator_name + str ;
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                 RichText(
                    text: TextSpan(
                      text: txt ,
                      style: TextStyle(
                        color: UIColor.color_primary,
                        fontSize: 14.rpx,
                      ),
                      children: const [
                        // TextSpan(
                        //     text: record.car_no, style: const TextStyle(color: UIColor.color_primary)),
                         TextSpan(text: " 装货完成, 配送中", style: TextStyle(color: UIColor.color_t1)),
                      ],
                    ),
                  ),
                  //UText.get(txt, UIColor.color_primary, 14.rpx),
                  4.hspace,
                  UText.get(record.created_time, UIColor.color_t3, 12.rpx),
                  8.hspace,
                  ..._renderImages(record.images,record),
                ],
              )
          )
          // Expanded(
          //   child: Column(
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     children: [
          //       8.hspace,
          //       UText.get(record.desc, UIColor.color_t1, 14.rpx),
          //       4.hspace,
          //       UText.get(record.created_time, UIColor.color_t3, 12.rpx),
          //       8.hspace,
          //       ..._renderImages(record.images,record),
          //     ],
          //   ),
          // ),
        ],
      ),
    );
  }

  List<Widget> _renderImages(List? iamges,WaybillRecordModel record) {
    if (iamges == null || iamges.isEmpty) {
      return [0.hspace];
    }
    var imgWidth = 64.rpx;
    return [
      SizedBox(
        height: imgWidth,
        child: ListView.separated(
          scrollDirection: Axis.horizontal,
          separatorBuilder: (context, index) {
            return 10.wspace;
          },
          itemBuilder: (context, index) {
            return GestureDetector(
              onTap: () {
                OpenUtils.open(context, ImageViewerPage(iamges,record: record, index: index));
              },
              child: ExtendedImage.network(
                iamges[index],
                width: imgWidth,
                height: imgWidth,
                borderRadius: BorderRadius.circular(2.rpx),
                shape: BoxShape.rectangle,
                fit: BoxFit.cover,
                loadStateChanged: (state) {
                  switch (state.extendedImageLoadState) {
                    case LoadState.loading:
                      return Container(color: UIColor.color_image_holder);
                    case LoadState.failed:
                      return Container(color: UIColor.color_image_holder);
                  }
                  return null;
                },
              ),
            );
          },
          itemCount: iamges.length,
        ),
      ),
      8.hspace
    ];
  }
  Widget _render6(int index) {
    var record = records[index];
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  8.hspace,
                  UText.get(record.desc, UIColor.color_t1, 14.rpx),
                  4.hspace,
                  UText.get(record.created_time, UIColor.color_t3, 12.rpx),
                  8.hspace,
                ],
              ))
        ],
      ),
    );
  }

  Widget _render7(int index) {
    var record = records[index];
    // List<String> _strL = record.desc.split("(");
    // List<String> _strR =_strL[1].split(")");
    // List<String> _strL = record.desc.split("（");
    // print(_strL);
    // List<String> _strR =_strL[1].split("）");
    // print(_strR);
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  8.hspace,
                  UText.get(record.desc, UIColor.color_t1, 14.rpx),
                  // RichText(
                  //   text: TextSpan(
                  //     text: "车辆到达卸货地点（",
                  //     style: TextStyle(
                  //       color: UIColor.color_t1,
                  //       fontSize: 14.rpx,
                  //     ),
                  //     children: [
                  //       TextSpan(text: record.desc, style: const TextStyle(color: UIColor.color_primary) ),
                  //       const TextSpan(text: "），正在卸货", style: TextStyle(color: UIColor.color_t1)),
                  //     ],
                  //   ),
                  // ),
                  4.hspace,
                  UText.get(record.created_time, UIColor.color_t3, 12.rpx),
                  8.hspace,
                ],
              )
          )
        ],
      ),
    );
  }

  Widget _render9(int index) {
    var record = records[index];
    /// 主操作员 + 协作员
    String loaders = record.loaders;
    print(loaders);
    String str = "";
    if(loaders.isNotEmpty ) {
      List list = [];
      list = jsonDecode(loaders);
      list.forEach((element) {
        str = str + '、' + element["name"];
      });
    }
    var txt = record.operator_name + str ;
    return IntrinsicHeight(
      child: Row(
        children: [
          _renderLeftLine(index),
          12.wspace,
          Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  RichText(
                    text: TextSpan(
                      text: txt,
                      style: TextStyle(
                        color: UIColor.color_primary,
                        fontSize: 14.rpx,
                      ),
                      children: [
                        // TextSpan(
                        //     text: record.car_no, style: const TextStyle(color: UIColor.color_primary)),
                        const TextSpan(text: " 卸货完成, 签收成功", style: TextStyle(color: UIColor.color_t1)),
                      ],
                    ),
                  ),
                  //UText.get(txt, UIColor.color_primary, 14.rpx),
                  4.hspace,
                  UText.get(record.created_time, UIColor.color_t3, 12.rpx),
                  8.hspace,
                  ..._renderImages(record.images,record),
                ],
              )
          )
        ],
      ),
    );
  }
}